package com.ranyk.www.util;

import com.google.code.kaptcha.Constants;
import com.ranyk.www.security.AuthorizingUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;

/**
 * CLASS_NAME: SingletonLoginUtils.java <br/>
 *
 * @author ranyk           <br/>
 * @version V1.0           <br/>
 * @decription: 登录用户通用处理工具类  <br/>
 * @date: 2022-04-14 <br/>
 */
@Slf4j
public class SingletonLoginUtils {

    /**
     * 私有化无参构造器
     */
    private SingletonLoginUtils() {
        throw new AssertionError();
    }

    /**
     * 验证码校验
     *
     * @param registerCode 前端传入的验证码值
     * @return 匹配系统中存放的验证码和传入的验证码是不是一致, 相同一致则返回 true,同时移除 Session 中的验证码;否则返回 false;
     */
    public static boolean validate(String registerCode) {
        // 获取Session中验证码
        Object captcha = ServletUtils.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isEmpty(registerCode)) {
            return false;
        }
        boolean result = registerCode.equalsIgnoreCase(captcha.toString());
        if (result) {
            ServletUtils.getRequest().getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        }
        return result;
    }

    /**
     * 获取登录用户对象
     *
     * @return 返回获取到的用户对象, 如果没有获取到用户则返回 null;
     */
    public static AuthorizingUser getUser() {
        try {
            Subject subject = SecurityUtils.getSubject();
            AuthorizingUser user = (AuthorizingUser) subject.getPrincipal();
            if (user != null) {
                return user;
            } else {
                log.info("User not acquired!");
            }
        } catch (UnavailableSecurityManagerException e) {
            log.error("SingletonLoginUtils.getUser: ", e);
        }
        return null;
    }

    /**
     * 获取用户ID
     *
     * @return 返回获取到的用户ID, 如果没有获取到用户则返回 null;
     */
    public static Long getUserId() {
        try {
            AuthorizingUser user = getUser();
            if (user != null) {
                return user.getUserId();
            } else {
                log.info("User not acquired!");
            }
        } catch (UnavailableSecurityManagerException e) {
            log.error("SingletonLoginUtils.getUser: ", e);
        }
        return null;
    }

}
